from fastapi import APIRouter
from fastapi.responses import JSONResponse
from fastapi import Form
from starlette.responses import FileResponse
from starlette.responses import RedirectResponse
from database import get_user, get_logging, create_table_login_data, insert_login_data, get_login_data1, get_information, get_client_ip
from utils import name_mapping
from fastapi import Request, HTTPException
from pydantic import BaseModel
router = APIRouter()  # 创建一个路由器实例


@router.get("/login")
async def login():
    return FileResponse('static/login.html')


@router.post("/login")
async def login_post(request: Request,username: str = Form(...), password: str = Form(...)):
    create_table_login_data()
    ip_address = get_client_ip(request)
    print('ip', ip_address)
    # 验证用户名和密码
    user = get_user(username)

    # 定义错误响应模型
    class LoginError(BaseModel):
        message: str
        status_code: int = 400

    if not username or not password:
        insert_login_data(username, ip_address, 'failed')
        error = LoginError(message="账号或密码不能为空")
        return JSONResponse(status_code=error.status_code, content=error.dict())

    if not user or user['password'] != password:
        insert_login_data(username, ip_address, 'failed')
        error = LoginError(message="用户不存在或密码错误")
        return JSONResponse(status_code=error.status_code, content=error.dict())

    else:
        # 记录登录数据
        insert_login_data(username, ip_address, 'successful')
        return RedirectResponse(url=f"/login/{username}")


@router.post("/login/{username}")
async def login_user(username: str):
    return FileResponse('static/menu.html')  # 确保HTML文件位于static文件夹中


@router.post("/data")
async def data():
    data = get_login_data1()
    name = data['username']
    username = name_mapping.get(name, None)
    if username is None:
        return {"error": "Invalid username"}
    info = get_information(username)
    return info


@router.post("/data1")
@router.get("/data1")
async def data1():
    info = get_logging()
    return info

@router.get("/")
async def index():
    return RedirectResponse("/login")

def get_routes():
    return router